package com.config.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.config.entity.ShiftConfig;
import com.config.service.ShiftConfigService;


@Controller
@RequestMapping("/shiftConfig")
public class ShiftConfigController {

	@Resource(name="shiftConfigService")
	private ShiftConfigService service;
	
	
	/**
	 * 状态主界面
	 * @return
	 */
	@RequestMapping("/shiftConfigMain")
	public String stateMain(Model model){
		model.addAttribute("currentName","班次模式配置");
		return "config/shiftConfig";
	}
	
	/**
	 * treegrid的分页显示
	 * @param model
	 * @param id
	 * @param start
	 * @param limit
	 * @return
	 */
	@RequestMapping("/findByLineTreePage")
	public Model findByLineTreePage(Model model,
			@RequestParam(value="lineId",required=false)Integer lineId,
			@RequestParam(value = "page", required = false, defaultValue="0")int start,
			@RequestParam(value = "rows", required = false, defaultValue="10")int limit){
		List<ShiftConfig> list=service.findByLineTreePage(lineId, start, limit);
		int total=service.countByLineTreePage(lineId);
		model.addAttribute("rows",list);
		model.addAttribute("total",total);
		return model;
	}
	
	/**
	 * 查询指定生产线下的所有班制
	 * */
	@RequestMapping("/findByLine")
	public Map<String,Object> findByLine(int lineId){
		Map<String, Object> map = new HashMap<String, Object>();
		List<ShiftConfig> list=service.findShifts(lineId);
		if(list.size()>0){
			map.put("total",list.size() );
			map.put("items", list);
		}
		return map;
	}
	
	/**
	 * 查询指定班制下的所有班次
	 * */
	@RequestMapping("/findByShifts")
	public Map<String,Object> findByShifts(int fatherId){
		Map<String, Object> map = new HashMap<String, Object>();
		List<ShiftConfig> list=service.findByShiftsId(fatherId);
		if(list.size()>0){
			map.put("total",list.size() );
			map.put("items", list);
		}
		return map;
	}
	
	/**
	 * 更新
	 * */
//	@RequestMapping("/update")
//	public Map<String,Object> update(int id){
//		Map<String, Object> model = new HashMap<String, Object>();
//		ShiftConfig entity=service.getShiftConfig(id);
//		entity.setIsEffective("N");
//		service.update(entity);
//		model.put("success", true);
//		model.put("msg", "修改成功");
//		return model;
//	}
	
	/**
	 * 保存班制
	 * */
	@RequestMapping("/saveShifts")
	public Map<String,Object> saveShifts(int lineId,ShiftConfig e){
		Map<String, Object> model = new HashMap<String, Object>();
		//保存班制
		Date endTime=e.getEffectiveEndTime();
		Date startTime=e.getEffectiveStartTime();
		List<ShiftConfig> list=service.findShifts(lineId);
		if(list.size()==0){
			if(endTime.after(startTime)){
				service.save(e);
				model.put("success", true);
				model.put("msg", "保存班制成功");
			}else{
				model.put("success", false);
				model.put("msg", "保存班制失败,开始时间不能大于结束时间");
			}
		}else{
			//遍历获取最长的截止日期
			Date biggerEndDate=list.get(0).getEffectiveEndTime();
			//获取最早的有效开始日期
			Date biggerStartDate=list.get(0).getEffectiveStartTime();
			for(int i=0;i<list.size();i++){
				if((i+1)<list.size()){
					if(list.get(i+1).getEffectiveEndTime().after(biggerEndDate)){
						biggerEndDate=list.get(i+1).getEffectiveEndTime();
					}
					if(list.get(i+1).getEffectiveStartTime().before(biggerStartDate)){
						biggerStartDate=list.get(i+1).getEffectiveStartTime();
					}
				}
			}
			if(startTime.before(endTime)){
				if(endTime.before(biggerStartDate)||startTime.after(biggerEndDate)){
					service.save(e);
					model.put("success", true);
					model.put("msg", "保存班制成功");
				}else{
					model.put("success", false);
					model.put("msg", "保存班制失败，时间有重叠!");
				}
			}else{
				model.put("success", false);
				model.put("msg", "保存班制失败，开始时间不能大于结束时间！");
			}
		}
		return model;
	}
	
	
	/**
	 * 保存班次
	 * */
	@RequestMapping("/saveShift")
	public Map<String,Object> saveShift(ShiftConfig e){
		Map<String, Object> model = new HashMap<String, Object>();
		service.saveShift(e,model);
		return model;
	}
	
	
	
	/**
	 * 保存班制
	 * @param model
	 * @param entity
	 * @return
	 */
	@RequestMapping("/savebyShifts")
	public Model savebyShifts(Model model,ShiftConfig entity){
		int sequence=0;
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
		try {
			Date st=sdf.parse(entity.getStart());
			Date et=sdf.parse(entity.getEnd());
			if(st.compareTo(et)<0){
				sequence=service.countByLineTreePage(entity.getLineId());
				entity.setSequence(Integer.toString(sequence+1));
				entity.setEffectiveStartTime(st);
				entity.setEffectiveEndTime(et);
				entity.setIsEffective("N");
				service.save(entity);
				model.addAttribute("success",true);
				model.addAttribute("msg","班制添加成功");
			}else{
				model.addAttribute("success",false);
				model.addAttribute("msg","保存失败,开始时间不能大于结束时间");
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return model;
	}
	
	@RequestMapping("/load")
	public Model load(Model model,Integer id){
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
		SimpleDateFormat sdfs = new SimpleDateFormat("HH:mm");
		ShiftConfig entity=service.getShiftConfig(id);
		if(entity.getFatherId()==null||entity.getFatherId().equals("")){
			entity.setStart(sdf.format(entity.getEffectiveStartTime()));
			entity.setEnd(sdf.format(entity.getEffectiveEndTime()));
		}else{
			entity.setStart(sdfs.format(entity.getStartTime()));
			entity.setEnd(sdfs.format(entity.getEndTime()));
		}
		model.addAttribute("data",entity);
		model.addAttribute("success",true);
		model.addAttribute("msg","加载成功");
		return model;
	}
	
	@RequestMapping("updatebyShifts")
	public Model update(Model model,ShiftConfig entity){
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
		try {
			Date st=sdf.parse(entity.getStart());
			Date et=sdf.parse(entity.getEnd());
			if(st.compareTo(et)<0){
				entity.setEffectiveStartTime(st);
				entity.setEffectiveEndTime(et);
				service.update(entity);
				model.addAttribute("success",true);
				model.addAttribute("msg","修改班制成功");
			}else{
				model.addAttribute("success",false);
				model.addAttribute("msg","修改失败,开始时间不能大于结束时间");
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return model;
	}

	/**
	 * 保存班次
	 * @param model
	 * @param entity
	 * @return
	 */
	@RequestMapping("/savebyShift")
	public Model savebyShift(Model model,ShiftConfig entity){
		int sequence=0;
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
		try {
			List<ShiftConfig> list=service.findByShiftsId(entity.getFatherId());
			Date st = sdf.parse("2016-01-01 "+entity.getStart());
			Date et = sdf.parse("2016-01-01 "+entity.getEnd());
			if(list.size()>0){//判断后续添加的时间刻度是否从02号开始
				Date flag=list.get(0).getStartTime();
				if(flag.compareTo(st)<0){//添加的开始时刻从01号开始
					entity.setStartTime(st);
					if(st.compareTo(et)<0){
						entity.setEndTime(et);
					}else{
						entity.setEndTime(sdf.parse("2016-01-02 "+entity.getEnd()));
					}
				}else{
					entity.setStartTime(sdf.parse("2016-01-02 "+entity.getStart()));
					if(st.compareTo(et)<0){
						entity.setEndTime(sdf.parse("2016-01-02 "+entity.getEnd()));
					}else{
						Calendar   calendar   =   new   GregorianCalendar(); 
					     calendar.setTime(flag); 
					     calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动 
						entity.setEndTime(calendar.getTime());
					}
				}
			}else{
				entity.setStartTime(st);
				if(st.compareTo(et)<0){
					entity.setEndTime(et);
				}else{
					entity.setEndTime(sdf.parse("2016-01-02 "+entity.getEnd()));
				}
			}
			sequence=service.countByFatherId(entity.getFatherId());
			entity.setSequence(Integer.toString(sequence+1));
			entity.setShiftType("");
			service.save(entity);
			model.addAttribute("success",true);
			model.addAttribute("msg","班次添加成功");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return model;
	}
	
	
	@RequestMapping("updatebyShift")
	public Model updatebyShift(Model model,ShiftConfig entity){
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
		try {
			List<ShiftConfig> list=service.findByShiftsId(entity.getFatherId());
			Date st = sdf.parse("2016-01-01 "+entity.getStart());
			Date et = sdf.parse("2016-01-01 "+entity.getEnd());
			if(list.size()>0){//判断后续添加的时间刻度是否从02号开始
				Date flag=list.get(0).getStartTime();
				if(flag.compareTo(st)<0){//添加的开始时刻从01号开始
					entity.setStartTime(st);
					if(st.compareTo(et)<0){
						entity.setEndTime(et);
					}else{
						entity.setEndTime(sdf.parse("2016-01-02 "+entity.getEnd()));
					}
				}else{
					entity.setStartTime(sdf.parse("2016-01-02 "+entity.getStart()));
					if(st.compareTo(et)<0){
						entity.setEndTime(sdf.parse("2016-01-02 "+entity.getEnd()));
					}else{
						Calendar   calendar   =   new   GregorianCalendar(); 
					     calendar.setTime(flag); 
					     calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动 
						entity.setEndTime(calendar.getTime());
					}
				}
			}else{
				if(st.compareTo(et)<0){
					entity.setStartTime(st);
					entity.setEndTime(et);
				}else{
					entity.setStartTime(st);
					entity.setEndTime(sdf.parse("2016-01-02 "+entity.getEnd()));
				}
			}
			entity.setShiftType("");
			service.update(entity);
			model.addAttribute("success",true);
			model.addAttribute("msg","班次修改成功");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return model;
	}
	
	/**
	 * 删除
	 * */
	@RequestMapping("/delete")
	public Model deleteShifts(Model model,Integer id){
		ShiftConfig entity=service.getShiftConfig(id);
		if(entity.getFatherId()==null){//班制
			if(entity.getIsEffective().equals("Y")){
				model.addAttribute("success",false);
				model.addAttribute("msg","不能删除有效的配置");
			}else{
				List<ShiftConfig> list=service.findByShiftsId(entity.getId());
				if(list.size()>0){
					for(ShiftConfig e:list){
						service.delete(e.getId());
					}
				}
				service.delete(id);
				model.addAttribute("success",true);
				model.addAttribute("msg","班制和班次均删除成功");
			}
		}else{//班次
			ShiftConfig e=service.getShiftConfig(entity.getFatherId());
			if(e.getIsEffective().equals("Y")){
				model.addAttribute("success",false);
				model.addAttribute("msg","不能删除有效的配置");
			}else{
				service.delete(id);
				model.addAttribute("success",true);
				model.addAttribute("msg","删除成功");
			}
		}
		return model;
	}
	
	/**
	 * 设置是否有效
	 * */
	@RequestMapping("/setEffective")
	public Model setEffective(Model model,Integer  id,Integer lineId){
		boolean flag=service.checkVertherRepeat(id);
		if(flag){
			//1.查找该生产线下是否有 在使用的记录, 若有 则设置为N
			ShiftConfig e=service.getEffectiveOne(lineId);
			if(e!=null){
				e.setIsEffective("N");
				service.update(e);
			}
			//2.设置修改的记录为Y
			ShiftConfig entity=service.getShiftConfig(id);
			entity.setIsEffective("Y");
			service.update(entity);
			model.addAttribute("success",true);
			model.addAttribute("msg","修改成功");
		}else{
			model.addAttribute("success",false);
			model.addAttribute("msg","失效，请确定时刻无重复且满足24小时");
		}
		return model;
	}
	
	/**
	 * 设置是否无效
	 * */
	@RequestMapping("/setNOEffective")
	public Model setNOEffective(Model model,Integer  id){
		ShiftConfig entity=service.getShiftConfig(id);
		entity.setIsEffective("N");
		service.update(entity);
		model.addAttribute("success",true);
		model.addAttribute("msg","修改成功");
		return model;
	}
	
}
